import axios from 'axios';
import store from '../stroes';
const CancelToken = axios.CancelToken;
axios.defaults.baseURL = '/api';
axios.defaults.headers['content-type'] = 'application/x-www-form-urlencoded'
axios.defaults.timeout = 50000;
const pendingList = [];

// 取消当前接口请求
export function cancelReq(){
  if (pendingList.length > 0) {
    pendingList.forEach((item) => {
      if (item.loading && item.c) {
        item.c();
      }
    })
  }
}

// 请求拦截器
axios.interceptors.request.use(config => {
  // console.log('请求前做点什么',config.isLogin)
  // if (pendingList.some(item => item.url === config.url)) {
  //   const target = pendingList.find(item => item.url === config.url);
  //   target.loading = config.cancelLoading ? false : true;
  //   config.cancelToken = new CancelToken(function executor(c){
  //     target.c = c;
  //   });
  // } else {
  //   pendingList.push({
  //     url: config.url,
  //     loading: config.cancelLoading ? false : true
  //   });
  //   config.cancelToken = new CancelToken(function executor(c){
  //     pendingList[pendingList.length - 1].c = c;
  //   });
  // }
  if(config.method == 'get'){
    let url =config.url +'?lang='+store.state.locale
    config.url = url
  }else if(config.method == 'post'){
    config.headers.lang = store.state.locale
  }
  config.headers['Authorization'] = store.state.Authorization
  return config;
}, error => {
  return Promise.reject(error);
});

// 响应拦截器
axios.interceptors.response.use(response => {
  let url = response.config.url
  if(response.config.method == 'get'){
    url = url.substring(0,url.length-11)
  }
  // console.log('1111',pendingList)
  // pendingList.find(item => item.url === url).loading = false;
  return response;
}, error => {
  // pendingList.find(item => item.url === error.config.url).loading = false;
  return Promise.reject(error);
});

const http = {
  get: function (url, params,lang, options = {}){
    return axios.get(url, { params, ...options });
  },
  postAdd: function (url, params, options = {}){
    return axios.post(url, params, options );
  },
  post: function (url, params, options = {}){
    return axios.post(url, params, options );
  },
  delete: function (url, params, options = {}){
    return axios.delete(url, { params, ...options });
  },
  put: function (url, params, options = {}){
    return axios.put(url, params, options );
  }
};

export default http;












